package learn_concurrent._2;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class T4 {
	final static Logger logger = LoggerFactory.getLogger(T4.class);

	public static void main(String[] args) throws InterruptedException {
//		ThreadUnsafe threadUnsafe = new ThreadUnsafe();
//		ThreadSafe threadSafe = new ThreadSafe();
		ThreadSafeSub threadSafeSub = new ThreadSafeSub();
		
		Runnable task = () -> threadSafeSub.method1();
		
		Thread t1 = new Thread(task);
		Thread t2 = new Thread(task);
		
		t1.start();
		t2.start();
	}

}

class ThreadUnsafe {
	private List<String> list = new ArrayList<>();

	public void method1() {
		for (int i = 0; i < 5000; i++) {
			method2();
			method3();
		}
	}

	public void method2() {
		list.add("1");
	}

	public void method3() {
		list.remove(0);
	}
}

class ThreadSafe {

	public void method1() {
		List<String> list = new ArrayList<>();
		for (int i = 0; i < 5000; i++) {
			method2(list);
			method3(list);
		}
	}

	public void method2(List<String> list) {
		list.add("1");
	}

	public void method3(List<String> list) {
		list.remove(0);
	}
}

class ThreadSafeUnOverried {

	public final void method1() {
		List<String> list = new ArrayList<>();
		for (int i = 0; i < 5000; i++) {
			method2(list);
			method3(list);
		}
	}

	private void method2(List<String> list) {
		list.add("1");
	}

	private void method3(List<String> list) {
		list.remove(0);
	}
}

class ThreadSafeSub extends ThreadSafe {

	@Override
	public void method3(List<String> list) {
		new Thread(() -> list.remove(0)).start();
	}
}
